<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 12px">
      <!-- 查询区域 -->
      <a-form-model :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }" layout="inline" @keyup.enter.native="onQuery">
        <a-form-model-item label="起止时间" style="min-width: 500px">
          <a-month-picker
            v-model="startValue"
            :disabled-date="disabledStartDate"
            format="YYYY-MM"
            placeholder="开始时间"
            @openChange="handleStartOpenChange"
          />
          <span style="padding: 0 10px">-</span>
          <a-month-picker
            v-model="endValue"
            :disabled-date="disabledEndDate"
            format="YYYY-MM"
            placeholder="结束时间"
            :open="endOpen"
            @openChange="handleEndOpenChange"
          />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
          <a-button type="primary" @click="onQuery"> 查询 </a-button>
          <a-button style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button type="primary" @click="handleExport()" :disabled="isDisabled">批量导出</a-button>
        <a-icon type="rollback" @click="handleCloseCurrentPage()" />
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <z-table
          ref="table"
          rowKey="id"
          :showAlert="false"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          :rowSelection="rowSelection"
          @selectedRowKey="onSelectedRow"
          @change="onTableChange"
        >
          <template slot="action" slot-scope="text, record">
            <a-button @click="handleDetails(record)" type="link" style="padding: 0">预览</a-button>
            <a-divider type="vertical" />
            <a-button
              @click="handleExport(record)"
              type="link"
              style="padding: 0"
              :disabled="record.isGenerate == 0"
              :title="record.isGenerate == 0 ? '报告未生成，不能导出' : ''"
              >导出</a-button
            >
            <a-divider type="vertical" />
            <a-button @click="handleUpdate(record)" type="link" style="padding: 0">更新</a-button>
          </template>
        </z-table>
      </div>
    </a-card>
    <div v-for="(item, index) in refNum" :key="index" style="opacity: 0; position: fixed; z-index: -1">
      <div ref="bscrollpdf" style="width: 100%; padding: 20px" :id="item.domName">
        <detail-iframe :reportDate="item.reportDate" @request-ok="requestOk" />
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import * as caseApi from '@/api/modules/case.js'
import { downLoadMix } from '@/utils/export-util/util'
import detailIframe from './detail-iframe.vue'
import exportHandle from '@/utils/export-util/pdf-canvas'
import JsZip from 'jszip'
import FileSaver from 'file-saver'

export default {
  inject: ['closeCurrent'],
  components: {
    detailIframe,
  },
  data() {
    return {
      startValue: null,
      endValue: null,
      endOpen: false,
      loading: false,
      isDisabled: true,
      pdfUploadBool: false,
      form: {},
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 50,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}`, //序号分页后连续
        },
        {
          title: '报告日期',
          dataIndex: 'reportDate',
          width: 100,
          align: 'center',
        },
        {
          title: '是否生成',
          dataIndex: 'isGenerate',
          width: 60,
          align: 'center',
          customRender: (text) => `${text == 1 ? '是' : text == 0 ? '否' : ''}`,
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          width: 100,
          align: 'center',
        },
        {
          title: '操作',
          width: 100,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
      refNum: [],
      refCheckData: [],
      receivesData: [],
    }
  },
  computed: {
    rowSelection() {
      return {
        getCheckboxProps: (record) => ({
          props: {
            // 报告未生成，不能导出
            disabled: record.isGenerate == 0,
          },
        }),
      }
    },
  },
  created() {},
  async mounted() {
    await this.onQuery()
    // await this.forData(this.pageData.records)
    // console.log(this.refNum)
    // console.log(this.refCheckData)
  },
  methods: {
    onSelectedRow(keys) {
      this.isDisabled = keys.length > 0 ? false : true
    },
    async onQuery() {
      this.pageFilter.pageNo = 1
      this.$set(this.form, 'startReportDate', this.startValue ? moment(this.startValue).format('YYYY-MM') : '')
      this.$set(this.form, 'endReportDate', this.endValue ? moment(this.endValue).format('YYYY-MM') : '')
      await this.refreshTable()
    },
    onResetForm() {
      this.form = {}
      this.startValue = null
      this.endValue = null
      this.onQuery()
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    async refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      this.loading = true
      let res = await caseApi.caseReportList(form)
      if (res.success) {
        this.loading = false
        this.pageData = res.result
        this.$refs.table.onClearRowKeys()
      } else {
        this.loading = false
      }
    },
    handleDetails(record) {
      this.$router.push({
        path: '/case/report/details',
        query: {
          reportDate: record.reportDate,
          isGenerate: record.isGenerate,
          reportFileAddress: record.reportFileAddress,
        },
      })
    },
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let fileList1 = selectList
        .map((v) => v.reportFileAddress)
        .filter((obj) => obj !== null && obj !== undefined && obj !== '')
      let fileList2 =
        record && Object.keys(record).length > 0 && record.reportFileAddress ? [record.reportFileAddress] : []
      let params = {
        fileList: selectList.length > 0 ? fileList1 : fileList2,
      }
      if (params.fileList.length === 0) {
        this.$message.warn('导出文件不存在！')
        return
      }
      this.$confirm({
        title: `是否确认导出报告？`,
        okText: '确定',
        onOk() {
          caseApi.exportReport(params).then(async (res) => {
            if (res && res.size > 0) {
              const fileName = '案件分析报告.zip'
              await downLoadMix(res, fileName)
            } else {
              that.$message.warn('导出失败！')
            }
          })
        },
      })
    },
    handleUpdate(record) {
      let that = this
      let obj = {
        id: record.id,
        reportDate: record.reportDate,
        token: this.$ls.get(ACCESS_TOKEN),
      }
      let ids = [record.id]
      let refCheckData = this.refCheckData.filter(item => ids.indexOf(item.id) > -1)
      this.$confirm({
        title: `是否确认重新生成报告？`,
        okText: '确定',
        async onOk() {
          // await that.plexPDFBase64(refCheckData)
          caseApi.updateReport(obj)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.refreshTable()
              } else {
                that.$message.warn(res.message)
              }
            })
            .catch((e) => {
              that.$message.warn('请求失败！')
            })
        },
      })
    },
    disabledStartDate(startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEndDate(endValue) {
      const startValue = this.startValue
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
    handleCloseCurrentPage() {
      // 注意：以下代码必须存在
      // inject:['closeCurrent'],
      this.$router.push('/case/report')
      this.closeCurrent()
    },
    async forData(records) {
      this.refNum = []
      this.refCheckData = []
      for (let i = 0; i < records.length; i++) {
        let item = records[i]
        let obj = {}
        obj.id = item.id
        obj.isGenerate = item.isGenerate
        obj.domName = `reportDetails-${item.reportDate}`
        obj.reportDate = item.reportDate
        obj.refs = ''
        obj.pdfBase64 = ''
        this.refNum.push(obj)
        this.refCheckData.push(obj)
      }
    },
    // 初始化-接收预览页加载请求完成
    requestOk(value) {
      this.receivesData.push(value)
      if(this.refCheckData.length === this.receivesData.length) {
        console.log('请求完成成功',JSON.stringify(this.receivesData))
        // 过滤只取生成状态为否的，截屏base64，上传服务
        let refCheckData = this.refCheckData.filter(item => [0].indexOf(item.isGenerate) > -1)
        this.plexPDFBase64(refCheckData)
      }
    },
    // 获取截屏base64，上传服务
    async plexPDFBase64(refCheckData) {
      if(refCheckData.length==0) return
      for (let i = 0; i < refCheckData.length; i++) {
        // let refDom = refCheckData[i].refs
        // let refDom = document.querySelector('#'+refCheckData[i].domName)
        let refDom = document.getElementsByClassName(refCheckData[i].domName)
        await exportHandle.successPDF(refDom).then((pdfBase64) => {
          refCheckData[i].pdfBase64 = pdfBase64
        })
        if (i === refCheckData.length - 1 && refCheckData[refCheckData.length - 1].pdfBase64) {
          break
        }
      }

      let base64 = refCheckData.map((item) => {
        return {
          base64: item.pdfBase64,
          date: item.reportDate,
        }
      })
      this.pdfUploadBool = true
      // 上传base64
      caseApi.generatePdf({ pdfList: base64 }).then((res) => {
        if (res.success) {
          this.pdfUploadBool = false
        }
      })
    },
    // 根据PDF Base64生成ZIP
    async plexJsZip(name) {
      var zip = new JsZip()
      // var pdfZip = zip.folder('pdf')
      // var imgZip = zip.folder('images')
      for (let ii = 0; ii < this.refCheckData.length; ii++) {
        await zip.file(this.refCheckData[ii].reportDate + '.pdf', this.refCheckData[ii].pdfBase64.split('base64,')[1], {
          base64: true,
        })
        // await imgZip.file('smile' + ii + '.jpg', this.refCheckData[ii].imageBase64.split('base64,')[1], { base64: true })
      }
      await zip.generateAsync({ type: 'blob' }).then(function (content) {
        FileSaver.saveAs(content, `${name}.zip`)
      })
    }
  },
  // watch: {
  //   refNum: function () {
  //     this.$nextTick(() => {
  //       for (let i = 0; i < this.$refs.bscrollpdf.length; i++) {
  //         this.refNum[i].refs = this.$refs.bscrollpdf[i]
  //       }
  //     })
  //   },
  // },
}
</script>
<style lang="less" scoped>
/deep/.table-operator {
  display: flex;
  justify-content: space-between;
}
</style>